package com.cn.esermis.config.sharding;

import com.cn.esermis.constant.Constant;
import com.cn.esermis.utils.TableCreator;
import com.cn.esermis.utils.TableUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
/**
 * 4.1version 精准分片
 * 根据月精准分片 --  插入数据、精准查找使用
 */
@Slf4j
@Component
public class MonthPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    /**
     * 每个月分一片
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        // 获取分片键值（create_time）
        Date createTime = shardingValue.getValue();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createTime);

        // 格式化表后缀：order_yyyyMM
        String tableSuffix = String.format("%04d%02d",
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1); // 月份从0开始，需+1

        // 匹配逻辑表对应的实际表名，如order_202310
        String logicTableName = shardingValue.getLogicTableName();
        String actualTableName = logicTableName + "_" + tableSuffix;
        return actualTableName;
    }
}